<template>
  <div class="inventory-duty-form">
    <el-form ref="myform" v-loading="loading" :model="formItem" :rules="rules" label-width="100px" size="mini">
      <el-divider content-position="left">基本信息</el-divider>
      <el-form-item label="盘点计划" prop="inventoryPlanName">
        <el-input v-model="formItem.inventoryPlanName" disabled />
      </el-form-item>
      <el-form-item label="任务名称" prop="name">
        <el-input v-model="formItem.name" placeholder="请输入任务名称" />
      </el-form-item>
      <el-form-item label="部门" prop="orgCodes">
        <treeselect
          key="orgTreeSelect"
          v-model="formItem.orgCodes"
          :multiple="false"
          :options="availableOganizationTree"
          placeholder="请选择部门"
          value-consists-of="ALL_WITH_INDETERMINATE"
          @select="selcetOrg"
          @input="clearOrg"
        />
      </el-form-item>
      <el-divider content-position="left" />
      <el-table
        :key="formItem.dutyResultsFlg"
        :loading="false"
        :data="tasksByDepartment"
      >
        <el-table-column v-for="column in tasksByDepartmentColumns" :key="column.key" :label="column.title" :prop="column.key" :width="column.width" :sortable="column.sortable">
          <template slot-scope="scope">
            <column-render :render="column.render" :row="scope.row" :column="column" />
          </template>
        </el-table-column>
        <el-table-column label="位置">
          <template slot-scope="scope">
            <treeselect
              key="locationTreeForSelectAssets"
              v-model="scope.row.locationCodes"
              :multiple="true"
              :options="availableLocationTree"
              value-consists-of="LEAF_PRIORITY"
              @input="inputChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="责任人" :width="200">
          <template slot-scope="scope">
            <el-select v-if="scope.row.count > 0" v-model="scope.row.account" size="mini" clearable placeholder="请选择责任人" @change="onDepartmentAccoiuntChange(scope.row)">
              <el-option v-for="item in scope.row.availableUsers" :key="item.username" :label="item.name" :value="item.username" />
            </el-select>
          </template>
        </el-table-column>
        <!-- <el-table-column label="已选数量" :width="120">
          {{ selectNum }}
        </el-table-column> -->
        <el-table-column label="已选资产" :width="200">
          <template slot-scope="scope">
            <el-button size="mini" icon="el-icon-plus" @click="onOpenAssetPageView(scope.row)">查看资产</el-button>
          </template>
          <!-- <el-tag v-for="column in formItem.dutyResults" :key="column.id" closable @close="deleteTag(column.id)">{{ column.name }}</el-tag> -->
        </el-table-column>
        <el-table-column label="选择资产" :width="200">
          <template slot-scope="scope">
            <el-button size="mini" icon="el-icon-plus" @click="onOpenAssetPage(scope.row)">选择资产</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <FormDialog v-if="assetSelDialogFormVisible" width="80%" title="查看盘点资产" :show="assetSelDialogFormVisible" :append-to-body="true" @on-ok="temporarySave" @on-cancel="onCloseAssetDialog">
      <el-tabs v-model="activeName">
        <el-tab-pane label="固定资产" name="first">
          <FixedAssetTable v-if="activeName === 'first'" ref="assetTable" :for-selection="true" :multiple-selected="true" :belongs="$attrs.belongs" categories="1" :management-org-code="selectedOrgCode" :org-search-show="false" :location-arr="selectedLocationCodeArr" :selected-asset="selectedAsset" />
        </el-tab-pane>
        <el-tab-pane label="低值易耗品" name="second">
          <FixedAssetTable v-if="activeName === 'second'" ref="assetTable" :for-selection="true" :multiple-selected="true" :belongs="$attrs.belongs" categories="2" :management-org-code="selectedOrgCode" :org-search-show="false" :location-arr="selectedLocationCodeArr" :selected-asset="selectedAsset" />
        </el-tab-pane>
      </el-tabs>
    </FormDialog>
    <ViewDialog v-if="assetSelDialogFormVisibleView" width="80%" title="查看盘点资产" :show="assetSelDialogFormVisibleView" :append-to-body="true" @on-cancel="onCloseAssetDialogView">
      <FixedAssetTableView :id="id" ref="assetTable" :for-selection="true" :multiple-selected="true" :belongs="$attrs.belongs" categories="1" :management-org-code="selectedOrgCode" :org-search-show="false" :location-arr="selectedLocationCodeArr" />
    </ViewDialog>
  </div>
</template>

<script>
import { detail as planDetail } from '@neu/dcam-ui/api/inventoryPlan'
import {
  create,
  update,
  detail
} from '@neu/dcam-ui/api/inventoryDuty'
import FormDialog from '@neu/biz-core/components/FormDialog'
import ViewDialog from '@neu/biz-core/components/ViewDialog'
import { tree } from '@neu/dcam-ui/api/location'
import { tree as organizationsTree } from '@neu/auth-ui/api/organization'
import FixedAssetTable from '@neu/dcam-ui/views/fixedAssetKJ/tables'
import FixedAssetTableView from '@neu/dcam-ui/views/fixedAssetViewKJ/tables'
import { count as fetchOrgAssetCount } from '@neu/dcam-ui/api/fixedAsset'
import { listByOrg as getUserListByOrgCode } from '@neu/auth-ui/api/user'
import { INVENTORY_DUTY_TYPE_LIST } from '@neu/dcam-ui/utils/constants'
import { create as createTem } from '@neu/dcam-ui/api/inventoryResultkj'
import { remove } from '@neu/dcam-ui/api/inventoryResultkj'
import { bus } from '../../../main'

// 定义一个表单原始项，原始设计时，可以一次设置多个部门，生成多个任务
// 目前的实现是一次只能设置一个部门，所有原来很多的数组存储结构仍然保留，但只存一个值
const formItem = {
  // 任务名
  name: '',
  status: 'created',
  // 计划ID
  inventoryPlanId: '',
  // 计划名称
  inventoryPlanName: '',
  // 部门编码列表（现在只存一个值）
  orgCodes: null,
  // 部门名称列表（现在只存一个值）
  orgNames: [],
  // 盘点负责人编码列表（现在只存一个值）
  accountCodes: [],
  // 盘点负责人名字列表（现在只存一个值）
  accountNames: [],
  // 部门盘点任务中，资产位置的限定条件（可以多选）
  locationCodes: [],
  dutyResults: [],
  type: 'department',
  differentTypes: 'KJ',
  dutyResultsFlg: 0
}
export default {
  name: 'InventoryPlanEditForm',
  components: {
    ViewDialog,
    FormDialog,
    FixedAssetTable,
    FixedAssetTableView
  },
  props: {
    planId: {
      required: true,
      type: Number,
      default: -1
    },
    // 根据id可判断是新建还是更新
    id: {
      required: false,
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      loading: false,
      // 编辑的表单内容
      formItem: {
        ...formItem
      },
      // 位置树数据
      availableLocationTree: [],
      // 组织树数据
      availableOganizationTree: [],
      // 表单验证规则
      rules: {
        name: [{
          required: true,
          message: '任务名称不能为空',
          trigger: 'blur'
        },
        {
          validator: function(rule, value, callback) {
            if (value.length > 100) {
              callback(new Error('最多可输入100个字符'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }],
        inventoryPlanId: [{
          required: true,
          message: '盘点计划不能为空',
          trigger: 'change'
        }],
        orgCodes: [{
          required: true,
          message: '部门不能为空',
          trigger: 'blur'
        }]
      },
      /** 是否显示资产选择对话框 */
      assetSelDialogFormVisible: false,
      /** 按部门创建的任务项数据。当前一次只支持设置一个部门的任务 */
      tasksByDepartment: [],
      /** 按部门创建的任务表格定义 */
      tasksByDepartmentColumns: [
        { title: '部门', key: 'orgName', width: '180' },
        { title: '资产数量', key: 'count', width: '120',
          render: (h, params) => { // 查看功能
            if (!params.row.count) {
              return h('span', {
                style: {
                  color: 'red'
                }
              }, params.row.count)
            } else {
              return h('span', params.row.count)
            }
          }
        }
      ],
      INVENTORY_DUTY_TYPE_LIST,
      activeName: 'first',
      // 暂存不确定的数据
      temporarySelection: [],
      // 确定的数据
      determineSelection: [],
      selectNum: 0,
      assetSelDialogFormVisibleView: false,
      selectedAsset: ''
      // temporarySaveData: []
    }
  },
  computed: {
    // 将组织树扁平化，方便查找
    flatOrgs: function() {
      const list = []
      recur(this.availableOganizationTree)
      // 递归
      function recur(children) {
        for (let i = 0; i < children.length; i++) {
          list.push(children[i])
          if (children[i].children) {
            recur(children[i].children)
          }
        }
      }
      return list
    },
    // 查看任务资产时，传递选中的部门代码
    selectedOrgCode: function() {
      return this.tasksByDepartment.length > 0 ? this.tasksByDepartment[0].orgCode : ''
    },
    // 查看任务资产时，传递选中的位置编码
    selectedLocationCodeArr: function() {
      return this.tasksByDepartment.length > 0 ? this.tasksByDepartment[0].locationCodes : []
    }
  },
  watch: {
    // 监控id的变化，初始化表单数据
    id: {
      handler(newVal, oldVal) {
        this.fetch()
      },
      immediate: true
    }
  },
  mounted() {
    bus.$on('temporarySelection', (databind) => {
      this.temporarySelection = databind
    })
    // bus.$on('temporarySave', (databind) => {
    // console.log('=========234234========')
    // this.$set(this.formItem, 'dutyResults', databind)
    // this.formItem.dutyResultsFlg++
    // that.formItem.assetsData = databind
    // })
  },
  created() {
    // 获取位置数据
    tree(this.$attrs.belongs).then(response => {
      this.availableLocationTree = response.data
    })
  },
  methods: {
    // 初始化表单数据
    fetch: async function() {
      const result = await organizationsTree(this.$attrs.belongs)
      this.availableOganizationTree = [result.data]
      if (this.id !== -1) {
        // 获取任务详情数据
        detail(this.id).then(response => {
          // 综合一下初始化表单内容
          this.initForm({
            id: response.data.inventoryPlanId,
            name: response.data.inventoryPlanName
          }, response.data)

          // 根据任务关联的部门，构造回显任务部门信息的基础数据
          this.formItem.orgCodes.forEach(org => {
            const o = this.findOrgInfo(org)
            this.selcetOrg(o)
          })
        })
      } else {
        if (this.planId > -1) {
          // 新建任务
          planDetail(this.planId).then(planInfo => {
            this.initForm(planInfo.data, formItem)
          })
        }
      }
    },
    // 初始化表单数据
    initForm(planInfo, taskInfo) {
      this.formItem = {
        ...taskInfo,
        inventoryPlanId: planInfo.id,
        inventoryPlanName: planInfo.name
      }
      this.selectNum = this.formItem.dutyResults.length
    },
    // 保存操作，返回promise，后续处理交由调用者处理
    save() {
      console.log('准备存储的设备:')
      if (this.formItem.type === 'department') {
        if (this.tasksByDepartment.filter(task => task.count > 0).length === 0) {
          this.$message({
            type: 'warning',
            message: '所选部门下都没有关联资产'
          })
          return new Promise(resolve => {
            resolve(false)
          })
        } else {
          const task = this.tasksByDepartment[0]
          this.formItem.orgCodes = [task.orgCode]
          this.formItem.orgNames = [task.orgName]
          // this.formItem.accountCodes = [task.account]
          // this.formItem.accountNames = [task.accountName]
          this.formItem.locationCodes = task.locationCodes
          this.formItem.account = task.account
          this.formItem.userName = task.accountName
        }
      }
      const updated = this.id !== -1
      return new Promise(resolve => {
        this.$refs.myform.validate((valid) => {
          if (valid) {
            if (updated) {
              // console.log(updated)
              this.formItem.differentTypes = 'KJ'
              resolve(update(this.id, this.formItem))
            } else {
              resolve(create(this.formItem))
            }
          } else {
            resolve(false)
          }
        })
      })
    },
    // 选择准备要盘点的部门
    selcetOrg(value) {
      // if (this.id !== -1) {
      // console.log('1 :' + this.formItem.orgCodes)
      // console.log('2 :' + value.code)
      // console.log(this.formItem.orgCodes === value.code)

      // console.log(encodeURIComponent(this.formItem.orgCodes))
      // console.log(encodeURIComponent(value.code))
      // console.log(encodeURIComponent(this.formItem.orgCodes) === encodeURIComponent(value.code))
      // debugger
      if (encodeURIComponent(this.formItem.orgCodes) !== encodeURIComponent(value.code)) {
        this.formItem.dutyResults = []
        this.formItem.locationCodes = []
        this.selectNum = 0
        remove(this.id).then(res => {
          console.log('清空成功')
        })
      }
      // }

      if (!value) {
        return
      }
      this.tasksByDepartment = []
      this.formItem.orgNames.push(value.title)
      // 构造列表任务项
      const taskInfo = {
        orgCode: value.code,
        orgName: value.title
      }
      const query = {
        s_managementOrgCode: value.code,
        s_belongs: this.$attrs.belongs
      }

      if (this.formItem.locationCodes && this.formItem.locationCodes.length > 0) {
        taskInfo.locationCodes = this.formItem.locationCodes
      }

      if (taskInfo.locationCodes && taskInfo.locationCodes.length > 0) {
        query.s_locationArr = taskInfo.locationCodes.join(',')
      }
      // 选择完部门后，实时查一下部门下资产的数量
      fetchOrgAssetCount(query).then(res1 => {
        // 部门下资产数量
        taskInfo.count = res1.data

        if (taskInfo.count > 0) {
          // 如果部门下存在资产，在查一下部门下的用户
          getUserListByOrgCode(value.code).then(res => {
            // 部门下所有人员
            taskInfo.availableUsers = res.data || res.data.map(it => {
              return {
                code: it.username,
                name: it.name
              }
            })
            const oldUser = taskInfo.availableUsers.filter(user => user.username === this.formItem.account)
            if (oldUser.length > 0) {
              taskInfo.account = oldUser[0].username
              taskInfo.accountName = oldUser[0].name
            } else {
              taskInfo.availableUsers.filter(user => {
                // 科技公司的【部门资产专管员】、总行的【部门资产管理员】，两个角色默认是任务的负责人
                const assetAdminRole = user.roles.find(role => role.code === 'kjDeptAssetAdmin' || role.code === 'slDeptAssetAdmin')
                if (assetAdminRole) {
                  taskInfo.account = user.username
                  taskInfo.accountName = user.name
                }
              })
            }
            this.tasksByDepartment.push(taskInfo)
          })
        } else {
          this.tasksByDepartment.push(taskInfo)
        }
        console.log(taskInfo)
      })
    },
    // 清空部门选项
    clearOrg(value) {
      if (!value) {
        this.formItem.orgCodes = null
        this.formItem.orgNames = []
        this.formItem.accountCodes = []
        this.formItem.accountNames = []
        this.formItem.locationCodes = []

        this.tasksByDepartment = []
      }
    },
    /** 重置表单 */
    reset() {
      this.$refs.myform.resetFields()
      this.formItem.userName = ''
      // this.formItem = { ...formItem }
    },
    temporarySave() {
      // if (this.id !== -1) {
      // debugger
      // for (var j = 0; j < this.temporarySelection.length; j++) {
      //   var num1 = 0
      //   for (var i = 0; i < this.formItem.dutyResults.length; i++) {
      //     if (this.temporarySelection[j].id === this.formItem.dutyResults[i].assetId || this.temporarySelection[j].id === this.formItem.dutyResults[i].id) {
      //       num1++
      //     }
      //   }
      //   if (num1 === 0) {
      //     this.formItem.dutyResults.push(this.temporarySelection[j])
      //   }
      // }
      console.log(this.formItem.dutyResults)
      console.log(this.temporarySelection)
      // this.formItem.dutyResults = this.temporarySelection
      for (var i = 0; i < this.temporarySelection.length; i++) {
        var num = 0
        for (var j = 0; j < this.formItem.dutyResults.length; j++) {
          if (this.formItem.dutyResults[j].code === this.temporarySelection[i].code) {
            num = 1
            // break
          }
        }
        if (num === 0) {
          this.formItem.dutyResults.push(this.temporarySelection[i])
        }
      }
      // } else {
      // debugger
      // 比较选择的设备是否由重复 没有重复的情况下可以添加
      // for (var k = 0; k < this.temporarySelection.length; k++) {
      // var num2 = 0
      // for (var l = 0; l < this.formItem.dutyResults.length; l++) {
      // if (this.temporarySelection[k].id === this.formItem.dutyResults[l].id) {
      // num2++
      // }
      // }
      // if (num2 === 0) {
      // this.formItem.dutyResults.push(this.temporarySelection[k])
      // }
      // }
      // }

      // bus.$emit('temporarySave', this.determineSelection)
      // this.determineSelection.push.apply(this.determineSelection, this.temporarySelection)
      this.formItem.dutyResultsFlg++
      // console.log('确定的数据:')
      // console.log(this.formItem.dutyResults)
      this.selectNum = this.formItem.dutyResults.length
      this.assetSelDialogFormVisible = false
      // this.selectedAsset = ''
      // if (this.id !== -1) {
      const data = {
        id: this.id,
        dutyResultsTem: this.formItem.dutyResults,
        type: this.formItem.type
      }
      createTem(data).then(res => {
        console.log(res)
      })
      // }
    },
    // 关闭资源查看对话框
    onCloseAssetDialog() {
      this.selectedAsset = ''
      this.assetSelDialogFormVisible = false
    },
    // 查看任务关联资产。打开资产对话框，并传递限定条件
    onOpenAssetPage(row) {
      const that = this
      console.log(that.formItem.dutyResults)
      // var codes = ''

      that.formItem.dutyResults.forEach(function(model) {
        if (that.selectedAsset === '') {
          that.selectedAsset = model.code
        } else {
          that.selectedAsset = that.selectedAsset + ',' + model.code
        }
      })
      this.assetSelDialogFormVisible = true
    },
    // 关闭资源查看对话框
    onCloseAssetDialogView() {
      this.assetSelDialogFormVisibleView = false
    },
    // 查看任务关联资产。打开资产对话框，并传递限定条件
    onOpenAssetPageView(row) {
      this.assetSelDialogFormVisibleView = true
    },
    // 根据编码查找部门信息(因为前段拿到的是组织树，所以查找稍微麻烦些)
    findOrgInfo(code) {
      return this.flatOrgs.find(it => it.code === code)
    },
    // 改变盘点任务责任人
    onDepartmentAccoiuntChange(taskInfo) {
      const user = taskInfo.availableUsers.find(it => it.username === taskInfo.account)
      const listItem = this.tasksByDepartment.find(it => it.orgCode === taskInfo.orgCode)
      if (user) {
        listItem.accountName = user.name
      } else {
        listItem.accountName = ''
      }
    },
    inputChange(row) {
      // debugger
      // this.formItem.dutyResults = []
      // remove(this.id).then(res => {
      //   console.log('清空成功')
      // })
      // this.selectNum = 0
      const query = { s_managementOrgCode: row.orgCode }
      if (row.locationCodes.length > 0) {
        query.s_locationArr = row.locationCodes.join(',')
      }
      fetchOrgAssetCount(query).then(res1 => {
        row.count = res1.data
      })
    },
    deleteTag(id) {
      for (var i = 0; i < this.formItem.dutyResults.length; i++) {
        if (id === this.formItem.dutyResults[i].id) {
          this.formItem.dutyResults.splice(i, 1)
          // console.log(this.formItem.dutyResultsFlg)
          this.formItem.dutyResultsFlg++
          this.selectNum = this.formItem.dutyResults.length
          // console.log(this.formItem.dutyResults)
          break
        }
      }
    }
  }
}
</script>

<style lang="scss">
  .inventory-duty-form {
    .el-table{
      overflow: visible;
    }
    .el-table .cell{
      overflow: visible;
    }
    .el-table__body-wrapper{
      overflow: visible;
    }
  }
</style>
